<template>
  <BasicModal :show="show" title="修改简历" width="35%" :widthComfirm="true" @comfirm="comfirm">
    <template #content>
      <div class="content">
        <a-form ref="formRef" layout='vertical' :model="form" :rules="rules">
          <a-form-item label="姓名：" name="userName">
            <a-input v-model:value="form.userName" placeholder="请填写姓名"></a-input>
          </a-form-item>
          <a-form-item label="性别：" name="sex">
            <a-radio-group v-model:value="form.sex" :options="sexOptions" />
          </a-form-item>
          <a-form-item label="证件类型：" name="certificateType">
            <a-select v-model:value="form.certificateType" show-search :filter-option="filterOption"
              placeholder="请选择证件类型" :options="certificateOptions">
            </a-select>
          </a-form-item>
          <a-form-item label="证件号码：" name="certificateNumber">
            <a-form-item-rest> <a-input v-model:value="form.certificateNumber"></a-input></a-form-item-rest>
          </a-form-item>
          <a-form-item label="电子邮箱：" name="email">
            <a-input v-model:value="form.email" placeholder="请填写邮箱"></a-input>
          </a-form-item>
          <a-form-item label="籍贯：" name="birthplace">
            <a-cascader v-model:value="form.birthplace" :options="useCascaderAreaData()" placeholder="请选择籍贯" />
          </a-form-item>
          <template v-if="store.currentResume.processSort < 23">
            <div class="title"><span class="line"></span> 教育经历</div>
            <span v-for="item in educationList" :key="item.subTitle">
              <template v-if="item.show">
                <div class="sub-title">
                  <span>教育经历-{{ item.subTitle }}</span>
                  <div class="del" v-if="item.subTitle != '本科'" @click="handleReduce(item)">
                    <span class="icon iconfont icon-shanchu"></span>
                    删除
                  </div>
                </div>
                <a-form-item label="学校名称：" :name="item.type + 'schoolName'">
                  <!-- <a-input v-model:value="form[item.type + 'schoolName']" placeholder="请填写学校名称" /> -->
                  <el-select :disabled="item.disabled" v-model="form[item.type + 'schoolName']" filterable remote
                    :allow-create="true" reserve-keyword clearable placeholder="请填写学校名称" :remote-method="(val: string) => {
                      getShcool(val, item);
                    }" :loading="item.loading" style="width: 100%">
                    <el-option v-for="a in item.options" :key="a.value" :label="a.label" :value="a.value"></el-option>
                    <template #loading>
                      <svg class="circular" viewBox="0 0 50 50">
                        <circle class="path" cx="25" cy="25" r="20" fill="none" />
                      </svg>
                    </template>
                  </el-select>
                </a-form-item>
                <div class="grid">
                  <a-form-item label="开始日期：" :name="item.type + 'educationalStartTime'">
                    <a-date-picker :disabled="item.disabled" style="width: 100%;" picker="month"
                      :default-picker-value="defaultYear" v-model:value="form[item.type + 'educationalStartTime']"
                      placeholder="请选择开始日期" value-format="YYYY-MM" :disabled-date="(cur: any) => {
                        return disabledDate(cur, item)
                      }" />
                  </a-form-item>
                  <span style="padding-top: 35px;text-align: center">-</span>
                  <a-form-item label="结束日期：" :name="item.type + 'educationalEndTime'">
                    <a-date-picker style="width: 100%;" :disabled="item.disabled" :default-picker-value="defaultYear"
                      picker="month" v-model:value="form[item.type + 'educationalEndTime']" placeholder="请选择结束日期"
                      value-format="YYYY-MM" :disabled-date="(cur: any) => {
                        return disabledDate(cur, item)
                      }" />
                  </a-form-item>
                </div>
                <a-form-item label="院系：" v-show="item.qualificationType != '高中'" :name="item.type + 'schoolDepartment'">
                  <a-input :disabled="item.disabled" v-model:value="form[item.type + 'schoolDepartment']"
                    placeholder="请填写院系" />
                </a-form-item>
                <a-form-item label="专业：" v-show="item.qualificationType != '高中'" :name="item.type + 'specialty'">
                  <a-input v-model:value="form[item.type + 'specialty']" :disabled="item.disabled"
                    placeholder="请填写专业" />
                </a-form-item>
              </template>

            </span>
            <div class="add-btn" @click="handleAdd" v-show="!educationList.every(el => el.show === true)">
              <img src="@/assets/images/join/add.png" alt="" />
              <span> 添加</span>
            </div>
          </template>
        </a-form>
      </div>
    </template>

  </BasicModal>
</template>

<script setup lang='ts'>
import { onMounted, ref, toRef, watch } from "vue"
import {
  ElSelect,
  ElOption,
} from 'element-plus';
import type { Rule } from 'ant-design-vue/es/form';
import BasicModal from "./BasicModal.vue";
import { useCascaderAreaData } from './data/area-data';
import { selectCommonConfigDetail, updateSystemUserResumes, selectUniversityDetail } from "@/api/application-details/index.ts";
import { comStores } from '@/store/common/comStore';
import dayjs from "dayjs";
const store = comStores();
import { message } from "ant-design-vue";
interface Options {
  label: string;
  value?: string | number
}
const show = ref<boolean>(false);

const form = ref<any>({
  userName: "",
  sex: "",
  certificateType: "",
  birthday: "",
  birthplace: "",
  email: "",
  certificateNumber: ""
})
const seniorSchool = ref<any>()
watch(() => show.value, (val) => {
  if (val) {
    form.value = JSON.parse(JSON.stringify(store.currentResume));
    console.log(form.value, 'form.value');
    const list = form.value.educationalList.filter(el => el.qualificationType != '高中')//不展示高中
    seniorSchool.value = form.value.educationalList.find(el => el.qualificationType == '高中')
    currentIndex.value = list.length - 1;
    list.forEach(a => {
      educationList.value.forEach(b => {
        if (a.qualificationType === b.qualificationType) {
          form.value[b.type + "schoolName"] = a.schoolName
          form.value[b.type + "educationalStartTime"] = a.educationalStartTime || ""
          form.value[b.type + "educationalEndTime"] = a.educationalEndTime || ""
          form.value[b.type + "schoolDepartment"] = a.schoolDepartment
          form.value[b.type + "specialty"] = a.specialty;
        }
      })
    })
    educationList.value.forEach(el => {
      rules[el.type + 'schoolName'] = [{ required: true, message: '请填写学校名称', trigger: ['change', 'blur'] }]
      rules[el.type + 'educationalStartTime'] = [{ required: true, message: '请选择开始时间', trigger: ['change', 'blur'] }]
      rules[el.type + 'educationalEndTime'] = [{ required: true, message: '请选择结束时间', trigger: ['change', 'blur'] }]
    });
  }
})
const defaultYear = ref(dayjs('2000', 'YYYY')); // 设置默认年份为2000
const filterOption = (input: string, option: any) => {
  return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const disabledDate = (current: any, item: any) => {
  const today = item.minDate?.setHours(0, 0, 0, 0) as number;
  const maxDay = item.maxDate?.setHours(0, 0, 0, 0) as number;
  return current && (current.valueOf() < today || current.valueOf() > maxDay);
};
const certificateOptions = ref<Options[]>([])
onMounted(() => {
  getOptions()
})

const validatecertificateNumber = (rule, value) => {
  if (!value) {
    return Promise.resolve();
  }
  const is = validateIdCard(value);
  if (!is) {
    return Promise.reject('请填写正确的证件号码');
  }
  return Promise.resolve();
};

function validateIdCard(idCard: string) {
  if (!idCard) return false;
  if (!form.value.certificateType) return false;
  // 这里可以添加更复杂的校验逻辑  
  if (form.value.certificateType == '中国-居民身份证') {
    const len = idCard.length;
    if (len !== 18) return false;
    // 国内身份
    return (/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/.test(idCard))
  } else if (form.value.certificateType == '护照') {
    // 通用护照 最少六位
    return (/^[A-Z0-9]{6,}$/.test(idCard))
  } else if (form.value.certificateType == '中国-港澳永久身份证') {
    // 港澳永久身份证
    return (/^[A-Z](?:\d{6}|\d{7})$/.test(idCard))
  } else if (form.value.certificateType == '中国-台胞证') {
    // 港澳永久身份证
    return (/^[A-Z0-9]{8,}$/.test(idCard))
  } else if (form.value.certificateType == '中国-港澳非永久身份证') {
    // 港澳非永久身份证
    return (/^[A-Z](?:\d|[A-Z]){6,9}$/.test(idCard))
  } else {
    return true;
  }
}
const rules: Record<string, Rule[]> = {
  userName: [{ message: '请填写姓名', trigger: 'change', required: true }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  certificateType: [{ required: false, message: '请选择证件类型', trigger: 'change' }],
  certificateNumber: [{ validator: validatecertificateNumber, trigger: 'change', required: false }],
  // birthday: [{ required: true, message: '请填写出生日期', trigger: 'change' }],
  // birthplace: [{ required: true, message: '请填写籍贯', trigger: 'change' }],
  // email: [{ required: true, message: '请填写邮箱', trigger: 'change' }],
};

const getOptions = async () => {
  const data = await selectCommonConfigDetail({ type: "CERTIFICATE" });
  let list: Options[] = [];
  if (data && data.code === '10000') {
    list = data.data.map((el) => {
      return {
        label: el.label,
        value: el.label,
      };
    });
    certificateOptions.value = list
  } else {
    message.error(data.msg)
  }
}

const sexOptions = ref<Options[]>([
  { label: '男', value: 0 },
  { label: '女', value: 1 },
])

const educationList = ref<any>([
  // { type: "S", show: true, subTitle: "高中", qualificationType: "高中", schoolName: "",  },
  { type: "R", show: true, subTitle: "本科", qualificationType: "本科", schoolName: "", educationalStartTime: "", educationalEndTime: "", schoolDepartment: "", specialty: "" },
  { type: "M", show: false, subTitle: "硕士", qualificationType: "硕士", schoolName: "", educationalStartTime: "", educationalEndTime: "", schoolDepartment: "", specialty: "" },
  { type: "D", show: false, subTitle: "博士", qualificationType: "博士", schoolName: "", educationalStartTime: "", educationalEndTime: "", schoolDepartment: "", specialty: "" },
]);


const currentIndex = ref<number>(0);
const handleAdd = () => {
  currentIndex.value++;
  if (currentIndex.value >= 2) {
    currentIndex.value = 2
  }
}

const handleReduce = (item) => {
  currentIndex.value--;
  if (currentIndex.value <= 0) {
    currentIndex.value = 0
  }
}
watch(() => currentIndex.value, (val) => {
  console.log(val, '===>val')
  educationList.value.forEach((el, index) => {
    el.show = index <= val
  });
})

const formRef = ref<any>(null)

const comfirm = async () => {
  // console.log(form.value)
  // const idcard =validateIdCard(form.value.certificateNumber);
  // console.log(idcard,'idcard')
  // if(!idcard) return message.error("请填写正确的证件号码")
  // return
  const res = await formRef.value.validate();
  if (!res) return;
  // formRef.value.resetFields();
  console.log(form.value);
  const { resumeId, userName, sex, email, birthday, certificateType, certificateNumber, birthplace, isRecommends, recommendsName, recommendsPhone } = form.value;
  console.log(birthplace, 'birthplace')
  let param: any = {
    resumesId: resumeId,
    userName,
    sex,
    email,
    birthday,
    birthplace: Array.isArray(birthplace) ? birthplace.join("/") : birthplace || "",
    isRecommends,
    recommendsName,
    recommendsPhone,
    certificateType,
    certificateNumber,
    operator: store.userInFor.userName,
  }
  const finalList = educationList.value.filter(item => item.show)
  if (store.currentResume.processSort < 23) {
    educationList.value.forEach(el => {
      el.schoolName = form.value[el.type + 'schoolName']?.trim();
      el.educationalStartTime = form.value[el.type + 'educationalStartTime'];
      el.educationalEndTime = form.value[el.type + 'educationalEndTime'];
      el.schoolDepartment = form.value[el.type + 'schoolDepartment'];
      el.specialty = form.value[el.type + 'specialty'];
    })
    if (seniorSchool.value) {
      param.educationalList = [seniorSchool.value, ...finalList];
    } else {
      param.educationalList = finalList
    }
  } else {
    param.educationalList = null;
  }

  const data = await updateSystemUserResumes(param);
  console.log(data, '===>data');
  if (data && data.code === '10000') {
    show.value = false;
    store.getResumeInfo(resumeId);
    message.success('操作成功')
  } else {
    message.error(data.msg);
  }
}
const getShcool = async (val: string, v: any) => {
  console.log(val, '===>val')
  v.options = await getUniversityDetail(val, v);
};

const getUniversityDetail = async (schoolName: string, v) => {
  console.log(schoolName, "val");
  if (schoolName === "") {
    schoolName = "北京";
  }
  v.loading = true
  const data: any = await selectUniversityDetail({ schoolName: schoolName }).finally(() => {
    v.loading = false
  })
  if (data && data.code === "10000") {
    const list = data.data.map((el) => {
      return {
        label: el.universityName,
        value: el.universityName,
      };
    });
    return list;
  } else {
    return [];
  }
};

defineExpose({ show })
</script>

<style lang="less" scoped>
.progress {
  display: flex;
  justify-content: end;
  margin: 24px 0;
  padding-top: 24px;
  ;
  font-weight: 400;
  font-size: 14px;
  color: #333333;

  .desc {
    font-weight: 400;
    font-size: 14px;
    color: #209EE4;

  }
}

.title {
  height: 28px;
  font-weight: 600;
  font-size: 20px;
  color: #333333;
  line-height: 23px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  display: flex;
  align-items: center;
}

.sub-title {
  height: 22px;
  font-weight: 500;
  font-size: 16px;
  color: #209EE4;
  line-height: 19px;
  display: flex;
  justify-content: space-between;
  margin: 16px 0;

  .del {
    font-weight: 400;
    color: #FF4242;
    line-height: 16px;
    text-align: left;
    cursor: pointer;
  }
}

.line {
  width: 4px;
  height: 20px;
  background: #209EE4;
  border-radius: 0px 0px 0px 0px;
  margin-right: 10px;
}

.add-btn {
  height: 56px;
  background: #f5f7fb;
  border-radius: 3px 3px 3px 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  color: #209ee4;

  img {
    width: 24px;
    height: 24px;
    margin-right: 10px;
  }
}

.grid {
  display: gird;
  grid-template-columns: 5fr 1fr 5fr;



}

:deep(.ant-form-item-label) {
  min-width: 80px;
  text-align: left;
}

.content {
  max-height: 70vh;
  width: 104%;
  padding-right: 4%;
  overflow: auto;
}
</style>